<script setup>
	import { computed, onMounted, ref, watch } from 'vue'
	import { message } from 'ant-design-vue'
	import { CopyOutlined, ReloadOutlined } from '@ant-design/icons-vue'
	import datasetApi from '@/views/plugin/dashboard/api/datasetApi'

	const props = defineProps({
		editor: {
			type: Object,
			required: true
		},
		dataConnectorId: {
			type: String,
			required: false
		}
	})

	const emit = defineEmits(['formula-applied'])

	// 公式分类系统
	const FORMULA_CATEGORIES = [
		{
			key: 'user',
			label: '用户相关',
			icon: '👤',
			description: '当前登录用户相关的动态公式'
		},
		{
			key: 'time',
			label: '时间相关',
			icon: '⏰',
			description: '日期时间相关的动态公式'
		}
		// {
		// 	key: 'system',
		// 	label: '系统相关',
		// 	icon: '⚙️',
		// 	description: '系统环境相关的动态公式'
		// },
		// {
		// 	key: 'custom',
		// 	label: '自定义公式',
		// 	icon: '🔧',
		// 	description: '用户自定义的计算公式'
		// }
	]

	// 预设公式定义
	const PRESET_FORMULAS = {
		user: [
			{
				key: 'current_user_id',
				name: '当前用户ID',
				description: '获取当前登录用户的ID，用于数据权限过滤',
				example: 'WHERE creator_id = ${current_user_id}',
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_name',
				name: '当前用户姓名',
				description: '获取当前登录用户的姓名',
				example: "SELECT '${current_user_name}' as operator_name",
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_account',
				name: '当前用户账号',
				description: '获取当前登录用户的账号',
				example: "WHERE account = '${current_user_account}'",
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_dept_id',
				name: '当前用户部门ID',
				description: '获取当前登录用户的部门ID，用于部门数据权限控制',
				example: 'WHERE dept_id = ${current_user_dept_id}',
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_dept_name',
				name: '当前用户部门名称',
				description: '获取当前登录用户的部门名称',
				example: "SELECT '${current_user_dept_name}' as dept_name",
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_nickname',
				name: '当前用户昵称',
				description: '获取当前登录用户的昵称',
				example: "SELECT '${current_user_nickname}' as nickname",
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_position_id',
				name: '当前用户职位ID',
				description: '获取当前登录用户的职位ID',
				example: 'WHERE position_id = ${current_user_position_id}',
				category: 'user',
				type: 'string'
			},
			{
				key: 'current_user_position_name',
				name: '当前用户职位名称',
				description: '获取当前登录用户的职位名称',
				example: "SELECT '${current_user_position_name}' as position_name",
				category: 'user',
				type: 'string'
			}
		],
		time: [
			{
				key: 'current_date',
				name: '当前日期',
				description: '获取当前日期（YYYY-MM-DD格式）',
				example: "WHERE DATE(create_time) = '${current_date}'",
				category: 'time',
				type: 'date'
			},
			{
				key: 'current_time',
				name: '当前时间',
				description: '获取当前时间（HH:mm:ss格式）',
				example: "WHERE TIME(create_time) <= '${current_time}'",
				category: 'time',
				type: 'time'
			},
			{
				key: 'current_datetime',
				name: '当前日期时间',
				description: '获取当前日期时间（YYYY-MM-DD HH:mm:ss格式）',
				example: "WHERE create_time <= '${current_datetime}'",
				category: 'time',
				type: 'datetime'
			},
			{
				key: 'current_year',
				name: '当前年份',
				description: '获取当前年份',
				example: 'WHERE YEAR(create_time) = ${current_year}',
				category: 'time',
				type: 'number'
			},
			{
				key: 'current_month',
				name: '当前月份',
				description: '获取当前月份',
				example: 'WHERE MONTH(create_time) = ${current_month}',
				category: 'time',
				type: 'number'
			},
			{
				key: 'current_week',
				name: '当前周',
				description: '获取当前周数',
				example: 'WHERE WEEK(create_time) = ${current_week}',
				category: 'time',
				type: 'number'
			}
		],
		// system: [
		// 	{
		// 		key: 'system_name',
		// 		name: '系统名称',
		// 		description: '获取当前系统名称',
		// 		example: "SELECT '${system_name}' as system_info",
		// 		category: 'system',
		// 		type: 'string'
		// 	},
		// 	{
		// 		key: 'system_version',
		// 		name: '系统版本',
		// 		description: '获取当前系统版本',
		// 		example: "SELECT '${system_version}' as version",
		// 		category: 'system',
		// 		type: 'string'
		// 	},
		// 	{
		// 		key: 'tenant_id',
		// 		name: '租户ID',
		// 		description: '获取当前租户ID（多租户系统）',
		// 		example: 'WHERE tenant_id = ${tenant_id}',
		// 		category: 'system',
		// 		type: 'string'
		// 	}
		// ],
		custom: []
	}

	// 响应式数据
	const selectedCategory = ref('user')
	const supportedFormulas = ref({})
	const loading = ref(false)

	// 计算属性
	const currentCategoryFormulas = computed(() => {
		const presetFormulas = PRESET_FORMULAS[selectedCategory.value] || []

		// 合并预设公式和后端支持的公式
		const mergedFormulas = [...presetFormulas]

		// 添加后端支持但预设中没有的公式
		Object.entries(supportedFormulas.value).forEach(([key, description]) => {
			if (!presetFormulas.find((f) => f.key === key)) {
				mergedFormulas.push({
					key,
					name: key.replace(/_/g, ' ').replace(/\b\w/g, (l) => l.toUpperCase()),
					description,
					example: `WHERE column = \${${key}}`,
					category: 'system',
					type: 'string'
				})
			}
		})

		return mergedFormulas
	})

	// 加载支持的公式列表
	const loadSupportedFormulas = async () => {
		if (!props.dataConnectorId) return

		loading.value = true
		try {
			const result = await datasetApi.getSupportedFormulas()
			supportedFormulas.value = result || {}
		} catch (error) {
			console.error('获取支持的公式列表失败:', error)
			message.error('获取公式列表失败')
		} finally {
			loading.value = false
		}
	}

	// 监听数据连接器ID变化
	watch(
		() => props.dataConnectorId,
		(newId) => {
			if (newId) {
				loadSupportedFormulas()
			}
		},
		{ immediate: true }
	)

	// 添加公式到编辑器
	const addFormula = (formula) => {
		if (!props.editor || !props.editor.cminstance) {
			message.warning('编辑器未准备就绪')
			return
		}

		const formulaText = `\${${formula.key}}`
		const cm = props.editor.cminstance
		const pos = cm.getCursor()
		cm.replaceRange(formulaText, pos)
		cm.setCursor(pos.line, pos.ch + formulaText.length)
		cm.focus()

		emit('formula-applied', { formula, text: formulaText, position: pos })
		message.success(`已插入公式: ${formulaText}`)
	}

	// 复制公式到剪贴板
	const copyFormula = async (formula) => {
		const formulaText = `\${${formula.key}}`
		try {
			await navigator.clipboard.writeText(formulaText)
			message.success('公式已复制到剪贴板')
		} catch (err) {
			message.error('复制失败，请手动复制')
		}
	}

	// 获取公式类型图标
	const getTypeIcon = (type) => {
		const icons = {
			string: '📝',
			number: '🔢',
			date: '📅',
			time: '⏰',
			datetime: '📅⏰',
			boolean: '✅'
		}
		return icons[type] || '📝'
	}

	// 组件挂载时加载数据
	onMounted(() => {
		if (props.dataConnectorId) {
			loadSupportedFormulas()
		}
	})

	// 暴露方法给父组件
	defineExpose({
		addFormula,
		loadSupportedFormulas,
		selectedCategory,
		currentCategoryFormulas
	})
</script>

<template>
	<div class="formula-helper">
		<!-- 分类导航 -->
		<!-- <div class="category-tabs">
			<a-tabs v-model:activeKey="selectedCategory" type="card" size="small">
				<a-tab-pane v-for="category in FORMULA_CATEGORIES" :key="category.key" :tab="category.label">
					<template #tab>
						<span>{{ category.icon }} {{ category.label }}</span>
					</template>
				</a-tab-pane>
			</a-tabs>
		</div> -->

		<!-- 公式列表 -->
		<div class="formula-list">
			<div class="formula-header">
				<span class="formula-count">共 {{ currentCategoryFormulas.length }} 个公式</span>
				<div class="header-actions">
					<a-button :loading="loading" size="small" type="text" @click="loadSupportedFormulas">
						<template #icon>
							<ReloadOutlined />
						</template>
					</a-button>
				</div>
			</div>

			<div v-if="loading" class="loading-container">
				<a-spin size="small" />
				<span>加载公式列表中...</span>
			</div>

			<div v-else class="formula-items">
				<div
					v-for="formula in currentCategoryFormulas"
					:key="formula.key"
					class="formula-item"
					@click="addFormula(formula)"
				>
					<div class="formula-content">
						<div class="formula-header-info">
							<div class="formula-name">
								<span class="type-icon">{{ getTypeIcon(formula.type) }}</span>
								{{ formula.name }}
							</div>
							<div class="formula-key">${{ formula.key }}</div>
						</div>
						<div class="formula-description">{{ formula.description }}</div>
						<div v-if="formula.example" class="formula-example">
							<span class="example-label">示例:</span>
							{{ formula.example }}
						</div>
					</div>
					<div class="formula-actions">
						<a-button size="small" type="text" @click.stop="copyFormula(formula)">
							<template #icon>
								<CopyOutlined />
							</template>
						</a-button>
					</div>
				</div>
			</div>
		</div>
	</div>
</template>

<style scoped>
	.formula-helper {
		width: 100%;
		max-width: 500px;
	}

	.category-tabs {
		margin-bottom: 12px;
	}

	.formula-list {
		max-height: 400px;
		overflow-y: auto;
	}

	.formula-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		padding: 8px 0;
		border-bottom: 1px solid #f0f0f0;
		margin-bottom: 8px;
	}

	.formula-count {
		font-size: 12px;
		color: rgba(0, 0, 0, 0.45);
	}

	.header-actions {
		display: flex;
		gap: 8px;
	}

	.loading-container {
		display: flex;
		align-items: center;
		justify-content: center;
		gap: 8px;
		padding: 20px;
		color: rgba(0, 0, 0, 0.45);
	}

	.formula-items {
		display: flex;
		flex-direction: column;
		gap: 8px;
	}

	.formula-item {
		display: flex;
		justify-content: space-between;
		align-items: flex-start;
		padding: 12px;
		border: 1px solid #d9d9d9;
		border-radius: 2px;
		cursor: pointer;
		transition: all 0.3s;
		background: #fff;
	}

	.formula-item:hover {
		border-color: #1890ff;
		box-shadow: 0 2px 8px rgba(24, 144, 255, 0.15);
	}

	.formula-content {
		flex: 1;
		min-width: 0;
	}

	.formula-header-info {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 4px;
	}

	.formula-name {
		display: flex;
		align-items: center;
		font-weight: 500;
		color: rgba(0, 0, 0, 0.85);
	}

	.type-icon {
		margin-right: 6px;
		font-size: 14px;
	}

	.formula-key {
		font-size: 11px;
		color: #1890ff;
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
		background: #f0f7ff;
		padding: 2px 6px;
		border-radius: 2px;
	}

	.formula-description {
		font-size: 12px;
		color: rgba(0, 0, 0, 0.65);
		margin-bottom: 6px;
	}

	.formula-example {
		font-size: 11px;
		color: rgba(0, 0, 0, 0.45);
		font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
	}

	.example-label {
		color: #1890ff;
		font-weight: 500;
	}

	.formula-actions {
		display: flex;
		gap: 4px;
		margin-left: 8px;
	}

	/* 深色主题适配 */
	@media (prefers-color-scheme: dark) {
		.formula-item {
			background: #1f1f1f;
			border-color: #434343;
		}

		.formula-item:hover {
			border-color: #1890ff;
			background: #111b26;
		}

		.formula-key {
			background: #111b26;
			color: #69c0ff;
		}
	}
</style>
